package com.wbs.lease.web.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wbs.lease.common.constant.RedisConstant;
import com.wbs.lease.common.exception.LeaseException;
import com.wbs.lease.common.result.ResultCodeEnum;
import com.wbs.lease.common.utils.JwtUtil;
import com.wbs.lease.model.entity.SystemUser;
import com.wbs.lease.model.enums.BaseStatus;
import com.wbs.lease.web.admin.mapper.SystemUserMapper;
import com.wbs.lease.web.admin.service.LoginService;
import com.wbs.lease.web.admin.vo.login.CaptchaVo;
import com.wbs.lease.web.admin.vo.login.LoginVo;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;

    /**
     * 获取验证码,存入redis
     * @return
     */
    @Override
    public CaptchaVo getCaptcha() {

        //获取一个验证码的图片
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);

        //获取验证码的值（统一转为小写）
        String code = specCaptcha.text().toLowerCase();

        //为每一个验证码生成一个唯一的key,存入redis
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        redisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC , TimeUnit.SECONDS);

        //将验证码图片通过base64编码得到的字符串返回给前端
        String images = specCaptcha.toBase64();

        return new CaptchaVo(images, key);
    }


    /**
     * 登录,成功返回token
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        //检验验证码是否为空
        if(loginVo.getCaptchaCode() == null || loginVo.getCaptchaCode().isEmpty()) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

        //检验验证码值code是否存在，不存在说明过期，给个异常
        //存在则检验是否正确
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + loginVo.getCaptchaKey();
        String code = redisTemplate.opsForValue().get(key);
        if(code == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if(!code.equals(loginVo.getCaptchaCode().toLowerCase())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //根据vo用户名查询用户
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserMapper.selectOne(systemUserLambdaQueryWrapper);

        //校验用户是否存在
        if(systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //校验用户状态是否激活
        if(!systemUser.getStatus().equals(BaseStatus.DISABLE)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //校验密码是否正确
        if (!DigestUtils.md5DigestAsHex(loginVo.getPassword().getBytes()).equals(systemUser.getPassword())){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //创建jwt，返回token
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }
}
